package ua.khpi.si.kit49.diploma.controllers;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import ua.khpi.si.kit49.diploma.service.RegistrationService;

/**
 * Handler that invoke after successful authentication
 * 
 * @author netstalk3r
 * 
 */
public class AuthenticationSuccessHandler extends
		SimpleUrlAuthenticationSuccessHandler {

	private static final Logger log = Logger
			.getLogger(AuthenticationSuccessHandler.class);

	private static final String ROLE_ADMIN = "ROLE_ADMIN";
	private static final String ROLE_USER = "ROLE_USER";

	@Autowired(required = true)
	RegistrationService registrationService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		Set<String> roles = AuthorityUtils.authorityListToSet(authentication
				.getAuthorities());

		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		log.info("Login: user name - " + user.getUsername() + "; role - "
				+ roles.iterator().next());

		if (roles.contains(ROLE_ADMIN)) {
			request.getSession().setAttribute("role",
					"company.roles.role.admin");
			request.getSession().setAttribute("admin", true);
		} else {
			if (roles.contains(ROLE_USER)) {
				request.getSession().setAttribute("role",
						"company.roles.role.user");
				request.getSession().setAttribute("admin", false);
			}
		}

		request.getSession().setAttribute("username", user.getUsername());

		SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(
				request, response);

		if (savedRequest != null) {
			setDefaultTargetUrl(savedRequest.getRedirectUrl());
		}

		super.onAuthenticationSuccess(request, response, authentication);
	}

}
